package com.czx.reflection.controller;

import com.czx.reflection.pojo.User;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//动态的创建对象，通过反射
public class test03 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得Class对象
        Class c1 = Class.forName("com.czx.reflection.pojo.User");

        //构造一个对象
        User user = (User)c1.newInstance();//本质是调用了类的无参构造器
        System.out.println(user);

        //通过构造器获得对象
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user1 = (User) constructor.newInstance("陈泽熙", 32, 001);
        System.out.println(user1);


        //通过反射调用普通方法
        User user3 = (User)c1.newInstance();
        Method setName = c1.getDeclaredMethod("setName", String.class);
        //invoke激活的意思
        setName.invoke(user3,"泽熙");
        System.out.println(user3.getName());

        //通过反射调用属性
        User user4 = (User)c1.newInstance();
        Field name = c1.getDeclaredField("name");
        //开启权限的检测，因为那么属性是私有的。设置为true后就相当于开启了
        name.setAccessible(true);
        name.set(user4,"泽熙2");
        System.out.println(user4.getName());

    }
}
